package com.bykj.property.config.common.aspect;


import com.bykj.property.config.common.exception.CustomException;
import com.bykj.property.sys.service.LogService;
import com.bykj.property.controller.vo.response.ErrorCode;
import com.bykj.property.model.SysUser;
import com.bykj.property.model.TbLog;
import com.bykj.property.util.HttpContextUtil;
import com.bykj.property.util.IPUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
* @author tycoding
* @date 2019-03-13
*/
@Aspect
@Component
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired
private LogService logService;

@Pointcut("@annotation(com.bykj.property.config.common.annotation.Log)")
public void pointcut() {
}

@Around("pointcut()")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws JsonProcessingException {
Object result = null;
long beginTime = System.currentTimeMillis();
try {
result = proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
throw new CustomException(ErrorCode.SYS_ERR);
}
//获取Request请求
HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
//设置IP地址
String ip = IPUtil.getIpAddr(request);
//记录时间（毫秒）
long time = System.currentTimeMillis() - beginTime;
//保存日志
SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
TbLog log = new TbLog();
log.setUsername(sysUser.getUsername());
log.setIp(ip);
log.setTime(time);
logService.saveLog(proceedingJoinPoint, log);
return result;
}
}